using System;
using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.FileProviders;

namespace Idp_Login
{
    public static class StaticFilesPathConfig
    {
        public static IApplicationBuilder UseStaticFilesWrap(this IApplicationBuilder app, IWebHostEnvironment env)
        {
            var path3WRoot = GetStaticFilesPath(env);
            if (path3WRoot != null)
            {
                app.UseStaticFiles(new StaticFileOptions()
                {
                    FileProvider = new PhysicalFileProvider(path3WRoot)
                });
            }

            return app;

        }

        internal static string GetStaticFilesPath(IWebHostEnvironment env, string pathDirectory = null, string nameDirectory = "wwwroot")
        {
            //if (string.IsNullOrEmpty(pathDirectory))
            //{
            //    pathDirectory = Directory.GetCurrentDirectory();
            //}
            //var path3WRoot = Path.Combine(pathDirectory, nameDirectory);
            //if (Directory.Exists(path3WRoot))
            //{
            //    return path3WRoot;
            //}

            //var di = new System.IO.DirectoryInfo(pathDirectory);
            //return di.Parent == null ? null : GetStaticFilesPath(di.Parent.FullName, nameDirectory);//递归


            string webRootPath = env.WebRootPath;
            string contentRootPath = env.ContentRootPath;

            //上面代码居然可以改成 while (true) 2333333
            while (true)
            {
                if (string.IsNullOrEmpty(pathDirectory))
                {
                    pathDirectory = Directory.GetCurrentDirectory();
                }

                var path3WRoot = Path.Combine(pathDirectory, nameDirectory);
                if (Directory.Exists(path3WRoot))
                {
                    Console.WriteLine($"wwwroot的目录为:{path3WRoot}");
                    //var dataProtect = services.AddDataProtection();
                    //dataProtect.PersistKeysToStackExchangeRedis(redis, "DataProtection-Keys");
                    Console.WriteLine($@"
注:如果当前代码所在的项目使用了 DataProtection(数据保护) 
services.AddDataProtection()
PersistKeysToStackExchangeRedis(redis, ""xxx"");
请注意:
仅在Linux的Docker下, 若是运行N个实例(开集群),请手动检查 Redis 中的Key为xxx里的对象里确保只有1条数据,如果是N条数据则说明 DataProtection(数据保护) 没生效 ,请不要使用当前代码/移动app.UseStaticFilesWrap()的顺序(我也不知道原因,部署掉坑里1周多...o(╥﹏╥)o).
");
                    return path3WRoot;
                }

                var di = new System.IO.DirectoryInfo(pathDirectory);
                if (di.Parent == null) return null;
                pathDirectory = di.Parent.FullName;
            }
        }
    }
}
